#!/usr/bin/env python3
"""
查看预处理结果脚本

分析预处理结果，显示相似帧信息等
"""

import sys
import json
from pathlib import Path

# 添加项目路径
project_root = Path(__file__).parent.parent
sys.path.insert(0, str(project_root / 'src'))
sys.path.insert(0, str(project_root))

from utils.logger import get_logger


def view_preprocessing_results():
    """查看预处理结果"""
    print("=" * 60)
    print("预处理结果分析")
    print("=" * 60)
    
    # 加载预处理结果
    results_file = Path("data/processed/segmentation/preprocessing_results.json")
    if not results_file.exists():
        print("❌ 预处理结果文件不存在")
        print("请先运行数据预处理")
        return
    
    with open(results_file, 'r', encoding='utf-8') as f:
        results = json.load(f)
    
    # 显示总体统计
    print("\n📊 总体统计:")
    total_samples = 0
    for dataset, result in results.items():
        if isinstance(result, dict) and 'valid_samples' in result:
            valid = result['valid_samples']
            total = result['total_samples']
            print(f"  {dataset}: {valid}/{total} 个样本")
            total_samples += valid
    
    print(f"  总计: {total_samples} 个有效样本")
    
    # 显示数据划分
    if 'splits' in results:
        print("\n📋 数据划分:")
        for split_name, samples in results['splits'].items():
            print(f"  {split_name}: {len(samples)} 个样本")
    
    # 分析EchoNet-Dynamic的相似帧信息
    if 'echonet_dynamic' in results:
        echonet_samples = results['echonet_dynamic'].get('samples', [])
        if echonet_samples:
            print(f"\n🎬 EchoNet-Dynamic 相似帧分析:")
            
            # 统计相似帧信息
            total_similar_groups = 0
            total_original_frames = 0
            total_key_frames = 0
            quality_scores = []
            
            for sample in echonet_samples:
                similar_groups = sample.get('similar_groups', [])
                total_similar_groups += len(similar_groups)
                total_original_frames += sample.get('original_frames', 0)
                total_key_frames += sample.get('num_frames', 0)
                quality_scores.append(sample.get('quality_score', 0))
            
            print(f"  总相似帧组数: {total_similar_groups}")
            print(f"  平均每视频相似组数: {total_similar_groups / len(echonet_samples):.1f}")
            print(f"  原始帧总数: {total_original_frames}")
            print(f"  关键帧总数: {total_key_frames}")
            print(f"  压缩比: {total_key_frames / total_original_frames * 100:.1f}%")
            print(f"  平均质量分数: {sum(quality_scores) / len(quality_scores):.3f}")
            
            # 显示前几个视频的详细信息
            print(f"\n📝 前5个视频详情:")
            for i, sample in enumerate(echonet_samples[:5]):
                print(f"  视频 {i+1} ({sample['id']}):")
                print(f"    原始帧数: {sample.get('original_frames', 0)}")
                print(f"    关键帧数: {sample.get('num_frames', 0)}")
                print(f"    质量分数: {sample.get('quality_score', 0):.3f}")
                similar_groups = sample.get('similar_groups', [])
                print(f"    相似帧组数: {len(similar_groups)}")
                if similar_groups:
                    print(f"    相似帧组: {similar_groups[:3]}...")  # 只显示前3组
    
    # 检查输出目录结构
    output_dir = Path("data/processed/segmentation")
    if output_dir.exists():
        print(f"\n📁 输出目录结构:")
        for subdir in output_dir.iterdir():
            if subdir.is_dir():
                file_count = len(list(subdir.rglob("*")))
                print(f"  {subdir.name}/: {file_count} 个文件")
                
                # 显示第一个子目录的内容
                if subdir.name == "echonet_dynamic":
                    video_dirs = [d for d in subdir.iterdir() if d.is_dir()]
                    if video_dirs:
                        first_video = video_dirs[0]
                        files = list(first_video.glob("*"))
                        print(f"    示例视频 ({first_video.name}):")
                        for file in files[:5]:
                            print(f"      - {file.name}")
    
    print(f"\n✅ 预处理结果分析完成!")
    print(f"结果保存在: {output_dir}")


def main():
    """主函数"""
    try:
        view_preprocessing_results()
    except Exception as e:
        print(f"❌ 分析失败: {e}")
        sys.exit(1)


if __name__ == "__main__":
    main()
